package com.songlanyun.modules.memberbill.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.enums.BillConstant;
import com.songlanyun.common.enums.IntegralConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import com.songlanyun.common.utils.custom.MathUtils;
import com.songlanyun.common.utils.custom.PatternUtils;
import com.songlanyun.config.ChainProperties;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.entity.UserIdentityAssetEntity;
import com.songlanyun.modules.account.entity.UserVerifiedEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.account.service.UserIdentityAssetService;
import com.songlanyun.modules.account.service.UserVerifiedService;
import com.songlanyun.modules.account.service.impl.UserIdentityAssetServiceImpl;
import com.songlanyun.modules.chain.service.ChainService;
import com.songlanyun.modules.integralrecord.entity.IntegralRecord;
import com.songlanyun.modules.integralrecord.service.IntegralRecordService;
import com.songlanyun.modules.memberbill.dao.SaleRefillVoucherBillDao;
import com.songlanyun.modules.memberbill.entity.SaleRefillVoucherBillEntity;
import com.songlanyun.modules.memberbill.service.SaleRefillVoucherBillService;
import com.songlanyun.modules.pointconfig.entity.PointConfig;
import com.songlanyun.modules.pointconfig.service.PointConfigService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service("yxtSaleRefillVoucherBillService")
public class SaleRefillVoucherBillServiceImpl extends ServiceImpl<SaleRefillVoucherBillDao, SaleRefillVoucherBillEntity> implements SaleRefillVoucherBillService {


    @Resource
    private UserIdentityAssetService userIdentityAssetService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private PointConfigService pointConfigService;

    @Autowired
    private IntegralRecordService integralRecordService;

    @Autowired
    private UserVerifiedService userVerifiedService;


    @Autowired
    private SaleRefillVoucherBillDao saleRefillVoucherBillDao;

    @Resource
    ChainService chainService;
    @Resource
    ChainProperties chainProperties;






    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long userId = MapUtil.getLong(params, "user_id");//会员id
        Integer billType = MapUtil.getInt(params, "bill_type");//收支类型
        String refillOrderCode = MapUtil.getStr(params, "refill_order_code");//充值卡订单
        String saleOrderCode = MapUtil.getStr(params, "sale_order_code");//消费订单

        IPage<SaleRefillVoucherBillEntity> page = this.page(
                new Query<SaleRefillVoucherBillEntity>().getPage(params),
                new LambdaQueryWrapper<SaleRefillVoucherBillEntity>()
                        .eq(userId != null, SaleRefillVoucherBillEntity::getUserId, userId)
                        .eq(billType != null, SaleRefillVoucherBillEntity::getBillType, billType)
                        .like(StringUtils.isNotBlank(refillOrderCode), SaleRefillVoucherBillEntity::getRefillOrderCode, refillOrderCode)
                        .like(StringUtils.isNotBlank(saleOrderCode), SaleRefillVoucherBillEntity::getSaleOrderCode, saleOrderCode)
                        .orderByDesc(SaleRefillVoucherBillEntity::getCreateTimeMillis)

        );

        return new PageUtils(page);
    }

    /**
     * 生成收入账单
     *
     * @param userIdentity 会员资产
     * @param addMoney     收入金额
     * @param innerMode    收入行为（0充值，1退款余回退）
     * @param outTradeNo   充值订单编号
     */
    @Override
    public void saveIncomeBill(UserIdentityAssetEntity userIdentity, BigDecimal addMoney, String outTradeNo, BillConstant.InnerMode innerMode) {
        SaleRefillVoucherBillEntity bill = new SaleRefillVoucherBillEntity();
        bill.setRemark(innerMode.getMsg());//账单说明
        bill.setBillType(BillConstant.BillMode.INCOME);//账单类型
        bill.setEntryBeforeBalance(userIdentity.getBalance().subtract(addMoney));//入帐前的余额
        bill.setEntryAfterBalance(userIdentity.getBalance());//入帐后的余额
        bill.setEntryValue(addMoney);//入帐的额度
        bill.setRefillOrderCode(outTradeNo);//充值订单编号

        bill.setInnerMode(innerMode);//收入的行为模式（0充值，1退款余回退）
        bill.setCreateTimeMillis(System.currentTimeMillis());//创建帐户的时间戳
        bill.setUserId(userIdentity.getId());//会员id

        saleRefillVoucherBillDao.insert(bill);
    }

    @Override
    public void saveIncomeBill(UserIdentityAssetEntity userIdentity, BigDecimal addMoney, String outTradeNo, BillConstant.InnerMode innerMode,String remark) {
        SaleRefillVoucherBillEntity bill = new SaleRefillVoucherBillEntity();
        bill.setRemark(remark);//账单说明
        bill.setBillType(BillConstant.BillMode.INCOME);//账单类型
        bill.setEntryBeforeBalance(userIdentity.getBalance().subtract(addMoney));//入帐前的余额
        bill.setEntryAfterBalance(userIdentity.getBalance());//入帐后的余额
        bill.setEntryValue(addMoney);//入帐的额度
        bill.setRefillOrderCode(outTradeNo);//充值订单编号或其它业务编号

        bill.setInnerMode(innerMode);//收入的行为模式（0充值，1退款余回退）
        bill.setCreateTimeMillis(System.currentTimeMillis());//创建帐户的时间戳
        bill.setUserId(userIdentity.getId());//会员id

        saleRefillVoucherBillDao.insert(bill);
    }

    /**
     * 生成支出账单
     *
     * @param userIdentity 会员资产
     * @param subMoney     支出金额
     * @param outTradeNo   充值订单编号
     * @param outerModel   支出行为（0普通消费）
     */
    @Override
    public void saveExpenditureBill(UserIdentityAssetEntity userIdentity, BigDecimal subMoney, String outTradeNo, BillConstant.OuterMode outerModel) {
        SaleRefillVoucherBillEntity bill = new SaleRefillVoucherBillEntity();
        bill.setRemark(outerModel.getMsg());//账单说明
        bill.setBillType(BillConstant.BillMode.EXPENDITURE);//账单类型
        bill.setEntryBeforeBalance(userIdentity.getBalance().add(subMoney));//入帐前的余额
        bill.setEntryAfterBalance(userIdentity.getBalance());//入帐后的余额
        bill.setEntryValue(subMoney);//入帐的额度

        bill.setSaleOrderCode(outTradeNo);//消费订单编号
        bill.setOuterMode(outerModel);//支出（0普通消费）
        bill.setCreateTimeMillis(System.currentTimeMillis());//创建帐户的时间戳
        bill.setUserId(userIdentity.getId());//会员id

        saleRefillVoucherBillDao.insert(bill);
    }

    @Override
    public void saveExpenditureVoucherBill(UserIdentityAssetEntity userIdentity, BigDecimal subMoney, String outTradeNo, BillConstant.OuterMode outerModel) {
        SaleRefillVoucherBillEntity bill = new SaleRefillVoucherBillEntity();
        bill.setRemark(outerModel.getMsg());//账单说明
        bill.setBillType(BillConstant.BillMode.EXPENDITURE);//账单类型
        bill.setEntryBeforeBalance(userIdentity.getBalance().add(subMoney));//入帐前的余额
        bill.setEntryAfterBalance(userIdentity.getBalance());//入帐后的余额
        bill.setEntryValue(subMoney);//入帐的额度

        bill.setSaleOrderCode(outTradeNo);//消费订单编号
        bill.setOuterMode(outerModel);//支出（0普通消费）
        bill.setCreateTimeMillis(System.currentTimeMillis());//创建帐户的时间戳
        bill.setUserId(userIdentity.getId());//会员id


        saleRefillVoucherBillDao.insert(bill);
    }

    @Override
    public void saveExpenditureBill(UserIdentityAssetEntity userIdentity, BigDecimal subMoney, String outTradeNo, BillConstant.OuterMode outerModel,String remark) {
        SaleRefillVoucherBillEntity bill = new SaleRefillVoucherBillEntity();
        bill.setRemark(remark);//账单说明
        bill.setBillType(BillConstant.BillMode.EXPENDITURE);//账单类型
        bill.setEntryBeforeBalance(userIdentity.getBalance().add(subMoney));//入帐前的余额
        bill.setEntryAfterBalance(userIdentity.getBalance());//入帐后的余额
        bill.setEntryValue(subMoney);//入帐的额度

        bill.setSaleOrderCode(outTradeNo);//消费订单编号
        bill.setOuterMode(outerModel);//支出（0普通消费）
        bill.setCreateTimeMillis(System.currentTimeMillis());//创建帐户的时间戳
        bill.setUserId(userIdentity.getId());//会员id

        saleRefillVoucherBillDao.insert(bill);
    }

    @Override
    public List<SaleRefillVoucherBillEntity> getUserBill(Long userId) {
        return this.saleRefillVoucherBillDao.selectList(
                new LambdaQueryWrapper<SaleRefillVoucherBillEntity>()
                        .eq(SaleRefillVoucherBillEntity::getUserId, userId)
                        .orderByDesc(SaleRefillVoucherBillEntity::getCreateTimeMillis)

        );
    }

    @Override
    public PageUtils getUserBillPage(Long userId, Map<String, Object> params) {
        Integer billType = MapUtil.getInt(params, "bill_type");

        IPage<SaleRefillVoucherBillEntity> page = this.page(
                new Query<SaleRefillVoucherBillEntity>().getPage(params),
                new LambdaQueryWrapper<SaleRefillVoucherBillEntity>()
                        .eq(SaleRefillVoucherBillEntity::getUserId, userId)
                        .eq(billType != null, SaleRefillVoucherBillEntity::getBillType, billType)
                        .orderByDesc(SaleRefillVoucherBillEntity::getCreateTimeMillis)
        );

        return new PageUtils(page);
    }

    /**
     * 增加金额  --生成收入账单
     *
     * @param userId     用户id
     * @param addMoney   收入金额
     * @param outTradeNo 充值订单编号
     * @param innerMode  收入行为（0充值，1退款余回退）
     */
    @Override
    public void addBalance(Long userId, BigDecimal addMoney, String outTradeNo, BillConstant.InnerMode innerMode) {

        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateBalance(userId, addMoney, true);
        //生成充值订单账单明细，保存收入账单
        this.saveIncomeBill(userIdentity, addMoney, outTradeNo, innerMode);
    }

    @Override
    public void addBalance(Long userId, BigDecimal addMoney, String outTradeNo, BillConstant.InnerMode innerMode,String remark) {

        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateVoucher(userId, addMoney, true);
        //生成充值订单账单明细，保存收入账单
        this.saveIncomeBill(userIdentity, addMoney, outTradeNo, innerMode,remark);
    }

    /**
     * 减少金额 --生成支出账单
     *
     * @param userId     用户id
     * @param subMoney   支出金额
     * @param outTradeNo 充值订单编号
     *                   outerModel   支出行为（0普通消费）
     */
    @Override
    public void subBalance(Long userId, BigDecimal subMoney, String outTradeNo, BillConstant.OuterMode outerModel) {

        //资产
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateBalance(userId, subMoney, false);

        //生成充值订单账单明细，保存支出账单
        this.saveExpenditureBill(userIdentity, subMoney, outTradeNo, outerModel);
    }

    @Override
    public void subBalance(Long userId, BigDecimal subMoney, String outTradeNo, BillConstant.OuterMode outerModel,String remark) {

        //资产
        UserIdentityAssetEntity userIdentity = userIdentityAssetService.updateBalance(userId, subMoney, false);

        //生成充值订单账单明细，保存支出账单
        this.saveExpenditureBill(userIdentity, subMoney, outTradeNo, outerModel,remark);
    }


}
